﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Permissions;
using Brjostagjof.Models;
using Brjostagjof.HelpFunctions;
using System.IO;
using System.Web.Security;
using Brjostagjof.email;

namespace Brjostagjof.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {

        #region Gagnagrunnstenging og global breytur
        IBrjostagjofRepository rep = null;
        public HomeController()
        {
            rep = new BrjostagjofRepository();
        }
        public HomeController(IBrjostagjofRepository m_rep)
        {
            rep = m_rep;
        }

        #endregion

        #region Forsíða*

            public ActionResult Index()
            {
                IndexViewModel result = new IndexViewModel();
                result.newsArticles = rep.GetAllNews().Take(10);
                result.articles = rep.GetAllArticles().Take(10);
                return View(result);
            }

        #endregion

        #region Fréttagreinar*

        public ActionResult Frettir()
        {
            var result = new NewsArticleViewModel();
            result.newsArticles = rep.GetAllNews().Take(20);
            return View(result);
        }

        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult CreateNewsArticle()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Professional")]
        /* Script input er meðhöndlað af ckeditor, þarf að vara sig á að nota ALLTAF <%: ekki <%= þegar titll er notaður  */
        [ValidateInput(false)]
        public ActionResult CreateNewsArticle(NewsArticleViewModel newNewsArticle)
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" +
                    User.Identity.Name + " ] not found.");
            }

            // Do whatever u want with the unique identifier.
            Guid guid = (Guid)user.ProviderUserKey;

            if (ModelState.IsValid == true)
            {
                newNewsArticle.newsArticle.Date = DateTime.Now;
                newNewsArticle.newsArticle.Draft = false;
                newNewsArticle.newsArticle.FullName = rep.GetName(guid);
                rep.SaveNewsArticle(newNewsArticle.newsArticle);

                newNewsArticle.subscribers = rep.GetAllSubscribers();
                Brjostagjof.email.Email.NewsArticleLogMessage(newNewsArticle);
                return RedirectToAction("Frettir");
            }
            else
            {
                ModelState.AddModelError("","Athuga með að fylla þarf í alla merkta reiti");
                return View(newNewsArticle);
            }
        }

        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult BreytaFrettaGrein(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new NewsArticleViewModel();
                result.newsArticle = (from na in rep.GetAllNews()
                                      where na.ID == id.Value
                                      select na).SingleOrDefault();
                return View(result);
            }
            else
            {
                return RedirectToAction("Frettir");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Professional")]
        /* Script input er meðhöndlað af ckeditor, þarf að vara sig á að nota ALLTAF <%: ekki <%= þegar titll er notaður  */
        [ValidateInput(false)]
        public ActionResult BreytaFrettaGrein(int? id, NewsArticleViewModel changedNewsArticle)
        {
            if (ModelState.IsValid == true)
            {
                if (id.HasValue == true)
                {
                    rep.UpdateNewsArticle(id.Value, changedNewsArticle.newsArticle);
                    return RedirectToAction("SynaFrett", new { id = id.Value });
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            else
            {
                ModelState.AddModelError("", "Það verður að fylla inn í alla merkta reiti");
            }
            return View(changedNewsArticle);
        }


        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult EydaFrettaGrein(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new NewsArticleViewModel();
                result.newsArticle = (from na in rep.GetAllNews()
                                      where na.ID == id.Value
                                      select na).SingleOrDefault();
                return View(result);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult EydaFrettaGrein(int? id, NewsArticleViewModel toDelete)
        {
            if (id.HasValue == true)
            {
                toDelete.newsArticle = (from a in rep.GetAllNews()
                                        where a.ID == id.Value
                                        select a).SingleOrDefault();
                MembershipUser user = Membership.GetUser(User.Identity.Name);

                /* Leyfir aðeins notanda sem skrifaði greinina, eða administrator að eyða út. */
                if (user.UserName == toDelete.newsArticle.InserterID || Roles.IsUserInRole("Administrator"))
                {
                    rep.DeleteNewsArticle(id.Value);
                    return RedirectToAction("Frettir");
                }
                else
                {
                    return RedirectToAction("Frettir");
                }
            }
            else
            {
                return RedirectToAction("Frettir");
            }
        }

        public ActionResult SynaFrett(int? id)
        {
            // Ef innihald er í færibreytu p_id þá er byrt frétt með því ID 
            // annars er redirect til baka í fréttalista
            if (id.HasValue == true)
            {
                var result = new NewsArticleViewModel();
                result.newsArticle = (from na in rep.GetAllNews()
                                      where na.ID == id.Value
                                      select na).SingleOrDefault();
                if (result.newsArticle == null)
                {
                    return RedirectToAction("Frettir");
                }
                return View(result);
            }
            else
            {
                return RedirectToAction("Frettir");
            }
        }

        #endregion Fréttagreinar

        #region Greinar**

        public ActionResult GreinarIFlokk(string flokkur, string returnUrl)
        {
            if (flokkur != null)
            {
                var result = new ArticleViewModel();
                result.articles = (from art in rep.GetAllArticles()
                                   where art.Category == flokkur
                                   orderby art.Date descending
                                   select art);
                result.category = (from c in rep.GetAllCategories()
                                   where c.Category1 == flokkur
                                   select c).SingleOrDefault();

                return View(result);
            }
            else
            {
                return RedirectToAction("GreinaFlokkar");
            }
        }

        public ActionResult GreinaFlokkar()
        {
            var result = new ArticleViewModel();
            result.categories = rep.GetAllCategories();
            result.articles = rep.GetAllArticles();
            return View(result);

        }

        [Authorize(Roles="Administrator,Professional")]
        public ActionResult SkrifaGrein()
        {
            var result = new ArticleViewModel();
            result.categories = rep.GetAllCategories();
            return View(result);
        }

        [HttpPost]
        /* Script input er meðhöndlað af ckeditor, þarf að vara sig á að nota ALLTAF <%: ekki <%= þegar titll er notaður  */
        [ValidateInput(false)]
        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult SkrifaGrein(ArticleViewModel newArticle)
        {

            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" + User.Identity.Name + " ] not found.");
            }
            Guid guid = (Guid)user.ProviderUserKey;

            if (ModelState.IsValid == true)
            {
                newArticle.article.Date = DateTime.Now;
                newArticle.article.FullName = rep.GetName(guid);
                
            // Þetta verður notað síðar ef það verður hægt að ritskoða greinar sem verða birtar.
            // Þar er er bool value fyrir delete aðgerð á greinum, greinar verða alltaf til í gagnagrunni en birstast ekki í lista
            // Og einnig er breyta sem telur hversu oft grein er sótt úr gagnagrunni
                newArticle.article.Draft = false;
                newArticle.article.IsDeleted = false;
                newArticle.article.Count = 0;
                rep.SaveArticle(newArticle.article);
                
            // Email sent á alla notendur sem eru skráðir sem áskrifendur.
                newArticle.subscribers = rep.GetAllSubscribers();
                Brjostagjof.email.Email.ArticleLogMessage(newArticle);
                return RedirectToAction("GreinaFlokkar");
            }
            else
            {
                ModelState.AddModelError("", "Athuga að fylla þarf í alla merkta reiti.");
            }
            newArticle.categories = rep.GetAllCategories();
            return View(newArticle);
        }

        public ActionResult SynaGrein(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new ArticleViewModel();
                result.article = rep.GetArticleById(id.Value);
                if (result.article == null)
                {
                    return RedirectToAction("GreinaFlokkar");
                }
                return View(result);
            }
            else
            {
                return RedirectToAction("Error");
            }
        }

        [HttpPost]
        /* Script input er meðhöndlað af ckeditor, þarf að vara sig á að nota ALLTAF <%: ekki <%= þegar titll er notaður  */
        [Authorize(Roles = "Administrator,Professional")]
        [ValidateInput(false)]
        public ActionResult BreytaGrein(int? id, ArticleViewModel changedArticle)
        {
            if (id.HasValue == true)
            {
                rep.UpdateArticle(id.Value, changedArticle.article);
                return RedirectToAction("SynaGrein", new { id = id.Value });
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult BreytaGrein(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new ArticleViewModel();
                result.article = (from na in rep.GetAllArticles()
                                  where na.ID == id.Value
                                  select na).SingleOrDefault();
                result.categories = rep.GetAllCategories();
                return View(result);
            }
            else
            {
                return RedirectToAction("Frettir");
            }
        }

        [Authorize(Roles="Administrator,Professional")]
        public ActionResult EydaGrein(  int? id )
        {
            if (id.HasValue == true)
            {
                var grein = new ArticleViewModel();
                grein.article = (from a in rep.GetAllArticles()
                                   where a.ID == id.Value
                                   select a).SingleOrDefault();
                return View( grein );
            }
            else
            {
                return Redirect(Request.UrlReferrer.LocalPath);
            }
        }

        [HttpPost]
        [Authorize(Roles="Administrator,Professional")]
        public ActionResult EydaGrein( int? id, ArticleViewModel grein )
        {
            if (id.HasValue == true)
            {
                grein.article = (from a in rep.GetAllArticles()
                                 where a.ID == id.Value
                                 select a).SingleOrDefault();
                MembershipUser user = Membership.GetUser(User.Identity.Name);
                if (user.UserName == grein.article.InserterID || Roles.IsUserInRole("Administrator"))
                {
                    rep.DeleteArticle(id.Value);
                    return RedirectToAction("GreinaFlokkar");
                }
                else
                {
                    return RedirectToAction("GreinaFlokkar");
                }
            }
            else
            {
                return RedirectToAction("GreinaFlokkar");
            }
        }

        #endregion

        #region Algengar Spurningar*
        
        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult SkrifaSpurningu()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles="Administrator,Professional")]
        public ActionResult SkrifaSpurningu(CommonQuestion questionToStore)
        {
            if (ModelState.IsValid == true)
            {
                rep.SaveCommonQuestion(questionToStore);
                return RedirectToAction("SpurtOgSvarad");
            }
            else
            {
                ModelState.AddModelError("", "Vinsamlegast athugaðu að merktir reitir meiga ekki vera tómir");
            }
            return View();
        }

        public ActionResult SpurtOgSvarad()
        {
            IEnumerable<CommonQuestion> result = rep.GetAllCommonQuestions();
            return View(result);
        }
        #endregion

        #region Flokkar*
        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult NyrFlokkur()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Professional")]
        public ActionResult NyrFlokkur(Category newCategory)
        {
            if (ModelState.IsValid == true)
            {
                rep.SaveCategory(newCategory);
            }
            else
            {
                ModelState.AddModelError("", "Vinsamlegast fylltu í merkta reiti.");
            }
            return View();
        }

        #endregion

        #region Hafa Samband*

        public ActionResult HafaSamband()
        {
            var result = new HafaSambandViewModel();
            result.admins = rep.GetAllAdmins();
            result.professionals = rep.GetAllProfessionals();
            return View(result);
        }

        #endregion

        #region Mitt Svæði

        [Authorize]
        public ActionResult MittSvaedi()
        {
            return View();
        }
        [Authorize]
        public ActionResult Thyngd()
        {
            return View();
        }
        [Authorize]
        public ActionResult Lengd()
        {
            return View();
        }
        [Authorize]
        public ActionResult StaerdBarns()
        {
            return View();
        }
        [Authorize]
        public ActionResult WhoKurfa()
        {
            return View();
        }
        [Authorize]
        public ActionResult PostListi()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult PostListi( SubscriberViewModel model )
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            var result = rep.GetUserInfoById((Guid)user.ProviderUserKey);
            result.Subscriber = model.acceptMail;
            rep.UpdateUserInfo(result);
            return RedirectToAction("MittSvaedi");
        }

        #endregion

        #region Other*

        public ActionResult UmBrjostagjof()
        {
            return View();
        }

        public ActionResult Styrkir()
        {
            return View();
        }

        public ActionResult Plakot()
        {
            return View();
        }

        #endregion

        #region Kannanir*

        [Authorize(Roles="Administrator")]
        public ActionResult BuaTilKonnun()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "Administrator")]
        public ActionResult BuaTilKonnun(Survey newSurvey)
        {
            if (ModelState.IsValid == true)
            {     
                newSurvey.DateAdded = DateTime.Now;
                rep.SaveSurvey(newSurvey);
                return RedirectToAction("Index");
            }
            else
            {
                ModelState.AddModelError("", "Það verður að fylla inn í alla merkta reiti");
                return View(newSurvey);
            }
        }

        #endregion

        #region Myndir

        [HttpPost]
        [Authorize]
        public ActionResult Upload(ImageViewModel img)
        {
            if (ModelState.IsValid == true)
            {
                /* Tekur við fæl gegnum form */
                HttpPostedFileBase file = Request.Files[0];
                /* Ef fæll inniheldur gögn þá les hún þau í Byte fylki */
                if (file.ContentLength > 0)
                {
                    /* Býr til Byte fylki af stærðinni sem gögnin eru löng */
                    byte[] arrFileData = new byte[file.ContentLength];
                    /* Upphafsstyllir fylkið með gögnunum úr file */
                    file.InputStream.Read(arrFileData, 0, file.ContentLength);
                    /* Vistar gögnin úr Byte fylkinu í Linq.Binary type, sem Linq notar til að geyma í sql grunni */
                    System.Data.Linq.Binary bin = new System.Data.Linq.Binary(arrFileData);

                    MembershipUser user = Membership.GetUser(User.Identity.Name);
                    if (user == null)
                    {
                        throw new InvalidOperationException("User [" +
                            User.Identity.Name + " ] not found.");
                    }

                    // Do whatever u want with the unique identifier.
                    Guid guid = (Guid)user.ProviderUserKey;

                    img.image.ImageData = bin;
                    img.image.DateAdded = DateTime.Now;
                    if (guid != null)
                    {
                        img.image.UploaderID1 = guid;
                    }
                    else
                    {
                        img.image.UploaderID1 = null;
                    }
                    img.image.MimeType = file.ContentType;
                    rep.SaveImage(img.image);
                }
                return Redirect(Request.UrlReferrer.LocalPath);
            }
            else 
            {
                return Redirect(Request.UrlReferrer.LocalPath);
            }
        }

        public ActionResult ShowImage(int? id)
        {
            if (id.HasValue)
            {
                var result = (from img in rep.GetAllImages()
                              where img.ID == id.Value
                              select img).SingleOrDefault();

                if (result != null)
                {
                    return this.Image(result.ImageData.ToArray(), result.MimeType);
                }

            }
            return View("NotFound");
        }

        [Authorize]
        public ActionResult SetjaInnMynd(string error)
        {
            if (String.IsNullOrEmpty(error) == true)
            {
                return View();
            }
            else
            { 
                ModelState.AddModelError("", error);
            }
            return View();
        }

        [Authorize]
        public ActionResult MyndirBarn(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new ImageViewModel();
                result.child = rep.GetChildByID(id.Value);
                result.image = new Image { ChildID = id.Value };
                return View(result);
            }
            else
            {
                return RedirectToAction("Bornin");
            }
        }

        [Authorize]
        public ActionResult MinarMyndir()
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" +
                    User.Identity.Name + " ] not found.");
            }

            // Do whatever u want with the unique identifier.
            Guid guid = (Guid)user.ProviderUserKey;
            var result = new ImageViewModel();
            result.images = rep.GetImageByUser(guid);
            return View(result);
        }

        #endregion

        #region Myndbönd

        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult UploadVideo(VideoViewModel vid)
        {

            /* Tekur við fæl gegnum form */
            HttpPostedFileBase file = Request.Files[0];
            /* Ef fæll inniheldur gögn þá les hún þau í Byte fylki */
            if (file.ContentLength > 0)
            {
                /* Býr til Byte fylki af stærðinni sem gögnin eru löng */
                byte[] arrFileData = new byte[file.ContentLength];
                /* Upphafsstyllir fylkið með gögnunum úr file */
                file.InputStream.Read(arrFileData, 0, file.ContentLength);

                /* Vistar gögnin úr Byte fylkinu í Linq.Binary type, sem Linq notar til að geyma í sql grunni */
                System.Data.Linq.Binary bin = new System.Data.Linq.Binary(arrFileData);

                vid.video.VideoData = bin;
                vid.video.DateAdded = DateTime.Now;
                vid.video.UploaderID = 1;
                vid.video.MimeType = file.ContentType;
                rep.SaveVideo(vid.video);
            }
            return Redirect(Request.UrlReferrer.LocalPath);

        }

        public ActionResult ShowVideo(int? id)
        {
            if (id.HasValue)
            {
                var result = (from vid in rep.GetAllVideos()
                              where vid.ID == id.Value
                              select vid).SingleOrDefault();

                if (result != null)
                {
                    return this.Image(result.VideoData.ToArray(), result.MimeType);
                }

            }
            return View("NotFound");
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult SkraMyndband()
        {
            return View();
        }

        public ActionResult Myndbond(int? id)
        {
            var result = new VideoViewModel();
            result.video = rep.GetVideoById(id);
            return View(result);
        }

        public ActionResult MyndbandaListi()
        {
            var result = new VideoViewModel();
            result.videos = rep.GetAllVideos();
            result.youtubes = rep.GetAllYT();
            return View(result);
        }

        #endregion

        #region YouTube

        public ActionResult ShowYT(int? id)
        {
            if (id.HasValue)
            {
                var result = rep.GetYTById(id.Value);

            }
            return View("NotFound");
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult SkraYouTubeUrl()
        {
            return View();
        }

        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult SkraYouTubeUrl(VideoViewModel ytUrl)
        {
            if (ModelState.IsValid == true)
            {
                rep.SaveYouTube(ytUrl.youtube);
                return RedirectToAction("Myndbandalisti");
            }

            else
            {
                ModelState.AddModelError("", "Vinsamlegast skráið YouTube link í merktan reit"); 
            }
            return View();
        }
        public ActionResult SynaYouTube(int? id)
        {
            var result = new VideoViewModel();
            result.youtube = rep.GetYTById(id);
            return View(result);
        }


        #endregion

        #region Children
        public ActionResult Bornin()
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" +
                    User.Identity.Name + " ] not found.");
            }

            // Do whatever u want with the unique identifier.
            Guid guid = (Guid)user.ProviderUserKey;

            ImageViewModel result = new ImageViewModel();
            result.children = rep.GetChildByParentid(guid);
            return View(result);
        }

        public ActionResult StofnaBarn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult StofnaBarn(ImageViewModel newChild)
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" +
                    User.Identity.Name + " ] not found.");
            }


            // Do whatever u want with the unique identifier.
            Guid guid = (Guid)user.ProviderUserKey;
            newChild.child.ParentID = guid;
            rep.SaveChild(newChild.child);
            return RedirectToAction("Bornin");

        }
        [HttpPost]
        public ActionResult BreytaBarni(int? id, ImageViewModel changedChild)
        {
            if (id.HasValue == true)
            {
                rep.UpdateChild(id.Value, changedChild.child);
                return RedirectToAction("Bornin", new { id = id.Value });
            }
            else
            {
                return RedirectToAction("Bornin");
            }
        }

        public ActionResult BreytaBarni(int? id)
        {
            if (id.HasValue == true)
            {
                var result = new ImageViewModel();
                result.child = (from c in rep.GetAllChildren()
                                where c.ID == id.Value
                                select c).SingleOrDefault();
                return View(result);
            }
            else
            {
                return RedirectToAction("Bornin");
            }
        }

        public ActionResult UpplysingarUmBarn(int? id)
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                return RedirectToAction("Index");
            }
            // Do whatever u want with the unique identifier.
            
            Guid guid = (Guid)user.ProviderUserKey;
            
            var result = new ImageViewModel();
            result.child = rep.GetChildByID(id.Value);
            result.images = rep.GetImageByChild(guid, id.Value);

            return View(result);
        }
        #endregion Children

        #region Ads
        public ActionResult BuaTilAuglysingu()
        {
            return View();
        }
        [HttpPost]
        public ActionResult BuaTilAuglysingu(Ad newAd)
        {
            if (ModelState.IsValid == true)
            {
                newAd.Date = DateTime.Now;
                rep.SaveAd(newAd);
                return RedirectToAction("Index");
            }
            else
            {
                ModelState.AddModelError("", "Það verður að fylla inn í alla merkta reiti");
                return View(newAd);
            }

        }
        [HttpPost]
        [Authorize]
        public ActionResult UploadAd(ViewModel newAd)
        {

            /* Tekur við fæl gegnum form */
            HttpPostedFileBase file = Request.Files[0];
            /* Ef fæll inniheldur gögn þá les hún þau í Byte fylki */
            if (file.ContentLength > 0)
            {
                /* Býr til Byte fylki af stærðinni sem gögnin eru löng */
                byte[] arrFileData = new byte[file.ContentLength];
                /* Upphafsstyllir fylkið með gögnunum úr file */
                file.InputStream.Read(arrFileData, 0, file.ContentLength);
                /* Vistar gögnin úr Byte fylkinu í Linq.Binary type, sem Linq notar til að geyma í sql grunni */
                System.Data.Linq.Binary bin = new System.Data.Linq.Binary(arrFileData);

                MembershipUser user = Membership.GetUser(User.Identity.Name);
                if (user == null)
                {
                    throw new InvalidOperationException("User [" +
                        User.Identity.Name + " ] not found.");
                }

                // Do whatever u want with the unique identifier.
                Guid guid = (Guid)user.ProviderUserKey;

                newAd.ad.Ad1 = bin;
                newAd.ad.Date = DateTime.Now;
                if (guid != null)
                {
                    newAd.ad.Submitter = guid;
                }
                else
                {
                    newAd.ad.Submitter = null;
                }
                newAd.ad.MimeType = file.ContentType;
                rep.SaveAd(newAd.ad);
            }
            return RedirectToAction("Admin");
        }

        public ActionResult ShowAd(int? id)
        {
            if (id.HasValue)
            {
                var result = (from ad in rep.GetAllAds()
                              where ad.ID == id.Value
                              select ad).SingleOrDefault();

                if (result != null)
                {
                    return this.Image(result.Ad1.ToArray(), result.MimeType);
                }

            }
            return View("NotFound");
        }
        #endregion Ads

        #region Static föll

        public ActionResult FaNafn()
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            if (user == null)
            {
                throw new InvalidOperationException("User [" +
                    User.Identity.Name + " ] not found.");
            }

            // Do whatever u want with the unique identifier.
            Guid guid = (Guid)user.ProviderUserKey;

            var result = rep.GetName(guid);
            return View(result);
        }

        public static Survey GetTheNewestSurvey()
        {
            var db = new BrjostagjofRepository();
            var result = db.GetNewestSurvey();
            return (result);
        }

        public static Ad GetTheNewestAd()
        {
            var db = new BrjostagjofRepository();
            var result = db.GetNewestAd();
            return (result);
        }

        #endregion

        #region Admin

        [Authorize(Roles = "Administrator")]
        public ActionResult Admin()
        {
            var result = new AdminViewModel();
            result.UserInfoList = rep.GetAllRoleRequests();
            result.popularArticles = (from p in rep.GetAllArticles()
                                     orderby p.Count descending
                                     select p).Take(10);
            result.deletedArticles = from dA in rep.GetAllDeletedArticles()
                                     where dA.IsDeleted == true
                                     select dA;
            result.deletedNewsArticles = from dNA in rep.GetAllDeletedNews()
                                         where dNA.IsDeleted == true
                                         select dNA;
            return View( result );
        }

        [HttpPost]
        [Authorize(Roles="Administrator")]
        public ActionResult GeraFagadila(AdminViewModel toChange)
        {
            var emailToSend = new
            {
                Success = "Umsókn þín um að gerast fagaðili á brjóstagjöf.is hefur verið samþykkt",
                Fail    = "Umsókn þín um að gerast fagaðili á brjóstagjöf.is hefur verið hafnað",
                Message = "Hafir þú einhverjar spurningar varðandi umsókn þína vinsamlegast hafðu samband við vefstjóra"
            };

            var user = rep.GetUserById((Guid)toChange.User.UserId);
            var userInfo = rep.GetUserInfoById((Guid)toChange.User.UserId);
            if (Roles.IsUserInRole(user.UserName, "Professional") == false && toChange.isDenied == false)
            {
                Roles.AddUserToRole(user.UserName, "Professional");
                Email.EmailTo(rep.GetUserInfoById(user.UserId), emailToSend.Message, emailToSend.Success);
            }
            else
            {
                Email.EmailTo(rep.GetUserInfoById(user.UserId), emailToSend.Message, emailToSend.Fail);
            }

            userInfo.fagadili = false;
            rep.UpdateUserInfo(userInfo);
            return RedirectToAction("Admin");
        }

        #endregion

    }
}
